package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.SupportMapFragment;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.longqinuo.mycarservice.BuildConfig;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.NetUtils;
import com.longqinuo.mycarservice.utils.PathUtils;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnHomeFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends SupportMapFragment implements View.OnClickListener,WeatherSearch.OnWeatherSearchListener {

    private ListView mListView;
    private SimpleAdapter mAdapter;
    private List<Map<String,String>> mNewsList;  //新闻集合
    private String cityName = "上海市";

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnHomeFragmentInteractionListener mListener;
    private LinearLayout mBreakQuery;
    private LinearLayout mAddGas;
    private LinearLayout mNearClear;
    private LinearLayout mHighSpeed;
    private LinearLayout mSecondHand;
    private LinearLayout mKeepServer;
    private TextView moreNews;

    private TextView cityView;
    private TextView publish;
    private TextView weather;
    private TextView Temperature;
    private TextView wind;
    private TextView humidity;
    private WeatherSearchQuery mquery;
    private WeatherSearch mweathersearch;
    private LocalWeatherLive weatherlive;
    //定位操作
    private AMapLocation mapLocation = null;
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode()!=0) {
                    //定位成功回调信息，设置相关信息
                    aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果
                    aMapLocation.getLatitude();//获取纬度
                    aMapLocation.getLongitude();//获取经度
                    aMapLocation.getAccuracy();//获取精度信息
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(aMapLocation.getTime());
                    df.format(date);//定位时间
                    //地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会地址信息，GPS定位不会返回地址信息。
                    String addressInfo = aMapLocation.getAddress();
                    Log.d(">>>>", "地址信息"+addressInfo);
                    aMapLocation.getCountry();//国家信息
                    String province = aMapLocation.getProvince();//省信息
                    String city = aMapLocation.getCity();//城市信息
                    Log.d(">>>>", "城市信息"+city);
                    cityView.setText(province+city);
                    searchliveweather(city);   //查询天气
                    aMapLocation.getDistrict();//城区信息
                    aMapLocation.getStreet();//街道信息
                    aMapLocation.getStreetNum();//街道门牌号信息
                    aMapLocation.getCityCode();//城市编码
                    aMapLocation.getAdCode();//地区编码
                    aMapLocation.getAoiName();//获取当前定位点的AOI信息
                }
                mLocationClient.stopLocation();//停止定位
                mLocationClient.onDestroy();//销毁定位
            }
        }
    };

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mLocationClient=new AMapLocationClient(getActivity());
        mLocationClient.setLocationListener(mLocationListener); //初始化定位参数
        mLocationOption = new AMapLocationClientOption(); //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_home_news);

        cityView = (TextView) view.findViewById(R.id.tv_city_home);  //城市显示
//        cityView.setText(cityname);
        publish = (TextView)view.findViewById(R.id.tv_publish_home);//发布时间
        weather = (TextView)view.findViewById(R.id.tv_weather_home);//天气
        Temperature = (TextView)view.findViewById(R.id.tv_temp_home);//温度
        wind=(TextView)view.findViewById(R.id.tv_wind_home);//风向
        humidity = (TextView)view.findViewById(R.id.tv_humidity_home);//湿度

        mBreakQuery = (LinearLayout)view.findViewById(R.id.home_break_query);
        mAddGas = (LinearLayout) view.findViewById(R.id.home_add_gas);
        mNearClear = (LinearLayout)view.findViewById(R.id.home_near_clear);
        mHighSpeed = (LinearLayout) view.findViewById(R.id.home_high_speed);
        mSecondHand = (LinearLayout) view.findViewById(R.id.ll_second_hand_home);
        mKeepServer = (LinearLayout) view.findViewById(R.id.ll_keep_server_home);
        moreNews = (TextView) view.findViewById(R.id.tv_more_news_list);
        mBreakQuery.setOnClickListener(this);
        mAddGas.setOnClickListener(this);
        mNearClear.setOnClickListener(this);
        mHighSpeed.setOnClickListener(this);
        mSecondHand.setOnClickListener(this);
        mKeepServer.setOnClickListener(this);
        moreNews.setOnClickListener(this);
        mNewsList = new ArrayList<>();
        mAdapter = new SimpleAdapter(getActivity(),mNewsList,R.layout.home_news_item,
                new String[]{"title"},new int[]{R.id.tv_text_item_home});  //初始化新闻列表适配器
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FragmentTransaction mTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                mTransaction.add(R.id.ll_main_layout,NewsDetailFragment.newInstance(mNewsList.get(position).get("content"),""),"NewsDetail");
                mTransaction.addToBackStack("NewsDetail");
                mTransaction.commit();
            }
        });
        getData(); //获取新闻数据



    }

    private void searchliveweather(String cityname) {          //使用高德接口查询天气
        mquery = new WeatherSearchQuery(cityname, WeatherSearchQuery.WEATHER_TYPE_LIVE);//检索参数为城市和天气类型，实时天气为1、天气预报为2
        mweathersearch=new WeatherSearch(getActivity());
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索
    }
    private void getData() {    //获取新闻列表数据
        new AsyncTask<Void,Void,String>() {

            @Override
            protected String doInBackground(Void... params) {

                return requestNews();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int showapi_res_code = jsonObject.getInt("showapi_res_code");
                    if (showapi_res_code == 0) {
                        JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body");
                        int ret_code = showapi_res_body.getInt("ret_code");
                        if (ret_code == 0) {
                            JSONObject pagebean = showapi_res_body.getJSONObject("pagebean");
                            JSONArray contentlist = pagebean.getJSONArray("contentlist");
                            for (int i = 0; i < 3; i++) {
                                JSONObject o = contentlist.getJSONObject(i);
//                                Log.d("数据", "数据"+o.toString());
                                String title = o.getString("title");

                                String content = o.toString();
                                Map<String,String> map = new HashMap<String, String>();
                                map.put("title",title);
                                map.put("content",content);
                                mNewsList.add(map);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute();
    }
    private String requestNews() {    //请求新闻接口
        String getData = "";
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add("channelId", "5572a109b3cdc86cf39001e5")   //频道ID
                .add("channelName", "汽车最新")     //频道名字
                .add("page","1")
                .add("needContent","0")   //不需要返回正文
                .add("needHtml", "0")       //正文不为html格式
                .build();

        Request request = new Request.Builder()
                .url(PathUtils.NEWS_CHANNEL)
                .header("apikey",PathUtils.BAIDU_API_KEY)
                .post(body)
                .build();
        try {
            okhttp3.Response  response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                getData = response.body().string();
                Log.d(">>>>>Get请求", getData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getData;
    }
    @Override
    public void onResume() {
        super.onResume();
        PathUtils.isNetConection = NetUtils.isConnected(getActivity());
        if (!PathUtils.isNetConection) {
            Toast.makeText(getActivity(), "当前网络未连接", Toast.LENGTH_SHORT).show();
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(View view) {
        if (mListener != null) {
            mListener.onHomeFragmentInteraction(view);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnHomeFragmentInteractionListener) {
            mListener = (OnHomeFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                onButtonPressed(v);  //将单击监听事件传递给MainActivity
                break;
        }
    }

    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
        if (rCode == 1000) {
            if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                weatherlive = weatherLiveResult.getLiveResult();
                String get = weatherlive.getReportTime();
                String dates[] = get.split(" ");
                publish.setText(dates[0]+"\n"+dates[1]+" 更新");  //发布时间
                weather.setText(weatherlive.getWeather());			//天气
                Temperature.setText(weatherlive.getTemperature()+"°");			//温度
                wind.setText(weatherlive.getWindDirection()+"风     "+weatherlive.getWindPower()+"级");		//风向
                humidity.setText("湿度         "+weatherlive.getHumidity()+"%");		//湿度
            }else {
                if (BuildConfig.DEBUG) Log.d("》》》》》", "天气获取为空");
            }
        }else {
            if (BuildConfig.DEBUG) Log.d("》》》》", "天气获取失败");
        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnHomeFragmentInteractionListener {
        // TODO: Update argument type and name
        void onHomeFragmentInteraction(View view);
    }
}
